package com.cloudlinkin.service.impl;

import com.alibaba.fastjson.JSON;
import com.cloudlinkin.constant.HfxSmsConstant;
import com.cloudlinkin.entity.HfxContactResult;
import com.cloudlinkin.entity.HfxSendResult;
import com.cloudlinkin.entity.OtherSmsSubmitBizBean;
import com.cloudlinkin.entity.QueueProvinceModel;
import com.cloudlinkin.service.IHfxSmsService;
import com.cloudlinkin.util.BizUtils;
import com.cloudlinkin.util.error.RecordingExceptionControl;
import com.cloudlinkin.util.hfx.HfxSmsSendUtil;
import com.cloudlinkin.util.redis._RedisQueue;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;


/***
 * 和飞信下发相关类
 */
@Service("hfxSmsServiceImpl")
@Scope("prototype")
public class HfxSmsServiceImpl implements IHfxSmsService, Runnable {

	@Autowired
	private HfxSmsSendUtil hfxSmsSendUtil;
	@Autowired
	private ContactsServiceImpl contactsService; // 获取联系人ID

	@Value("${hfx_sms_enterDeptId}")
	private String enterDeptId;
	/**redis队列工具*/
	private _RedisQueue queue = new _RedisQueue();
    protected final Logger log = Logger.getLogger(this.getClass());
	/**经分日志使用的时间格式*/
	private final SimpleDateFormat df_yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss");
	/**和飞信要拉取的队列名称*/
	private String hfxQueueName;

	public void setHfxQueueName(String hfxQueueName) {
		this.hfxQueueName = hfxQueueName;
	}


	@Override
	public void run() { // 循环拉取下发
		// 拉取队列中的数据


		OtherSmsSubmitBizBean biz;

		for (;;) {

			biz = new OtherSmsSubmitBizBean();
			String reqTime;
			String respTime = null;
			String jsonStr;
			String stat = null;
			String TaskID = null;
			QueueProvinceModel province;

			try {

				jsonStr = queue.brpop(hfxQueueName);
				log.info(hfxQueueName + "Consumption to the data");

				if (jsonStr != null) {

					log.info(hfxQueueName + "data != null");

					province = JSON.parseObject(jsonStr, QueueProvinceModel.class);

					// 优先记录经分 可记什么就记什么
					biz.setREQ_ID(province.getReqId());
					biz.setREF_ID(province.getRefId());
					biz.setREGISTERED_DELIVERY(String.valueOf(province.getRpttype()));
					biz.setMSG_LEVEL(String.valueOf(province.getPriority()));
					biz.setSRC_CHANNEL_ID(province.getExCode());
					biz.setDEST_TERMINAL_ID(province.getMobile());
					biz.setIH_GATEWAY(hfxQueueName);
					biz.setIH_ENTERPRISE_TIMESTAMP(province.getMttime());

					biz.setPK_TOTAL("1");
					biz.setPK_NUMBER("1");
					biz.setSMS_TYPE("8");

					// 请求时间
					reqTime = df_yyyyMMddHHmmss.format(System.currentTimeMillis());
					biz.setIH_TIMESTAMP(reqTime);// 请求时间
					// 开始调用发送接口
                    HfxSendResult hfxSendResult = null;
                    HfxContactResult hfxContactResult = null;
					try {

                        String content = new String(province.getContent(), "UTF-8");

                        log.info(province.getReqId() + " 下发内容: " + content);

						// 获取联系人ID 如果没有获取到  就重试三次
                      for (int j = 0; j < 3; j++) {
                            try {
                                hfxContactResult = contactsService.getContactId(enterDeptId, province.getMobile()); // province.getMobile()
                                if(hfxContactResult != null){
                                    break;
                                }
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                        log.info(province.getReqId() + " 获取联系人ID结果:" + JSON.toJSONString(hfxContactResult));
						if(hfxContactResult != null && StringUtils.isNotBlank(hfxContactResult.getContactId())){
                            String contactIds = hfxContactResult.getContactId(); // 获取联系人ID不为空
                            hfxSendResult = hfxSmsSendUtil.smsSend(content, contactIds);
                            log.info(province.getReqId() + " 下发结果:" + JSON.toJSONString(hfxSendResult));
                        }

                    } catch (Exception e) {
						log.error("", e);
					}
					// 请求结束时间
					respTime = df_yyyyMMddHHmmss.format(System.currentTimeMillis());

					// 获取联系人失败没有下发
					if(StringUtils.isBlank(hfxContactResult.getContactId())){
                        stat = HfxSmsConstant.RETURN_STATUS_1001; // 获取联系人失败 不在重试   记录日志
                    }

                    // 获取联系人成功 下发了
                    if (StringUtils.isNotBlank(hfxContactResult.getContactId())) {

                        //请求失败，或resp为null
                        if (hfxSendResult == null) {

                            stat = HfxSmsConstant.RETURN_STATUS_9999; // 未知的下发错误不再重试
                            // 下发失败
                        }

                        // 通道繁忙   手机号获取失败   重试
                        if (hfxSendResult != null && HfxSmsConstant.RETURN_MSG_1000.equals(hfxSendResult.getHfxStatus())) { // 下发失败

                            queue.lpush(hfxQueueName,jsonStr);

                            continue; // 入完队列后跳出本次循环
                        }

                        if (hfxSendResult != null) { //
                            stat = hfxSendResult.getHfxStatus();
                            TaskID = hfxSendResult.getTaskId();

                        }

                    }

					biz.setMSG_ID(TaskID);
					biz.setSMS_RESULT(stat);
				}

			} catch (Exception e) {

				RecordingExceptionControl.controlRecordingException("HfxSmsServiceImpl", e.getMessage());
			} finally {
				BizUtils.setSubmitLog(biz.toString() + "," + respTime); // 记录经分日志
			}
		}


	}
}
